package com.joey.audiopickerdemo;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.joeyzh.soundrecorder.AudioFragment;
import com.joeyzh.soundrecorder.utils.AudioPickerManager;
import com.joeyzh.soundrecorder.utils.PickerConfig;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Joey on 2019/3/21.
 *
 * @author by Joey
 */

public class MainActivity extends AppCompatActivity {

    AudioFragment pickerFragment;
    //    String path = "/DCIM/Camera/IMG_20190312_160924.jpg";
    String path = "/scan.png";

    public static String format(String original) {
        final Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(original);
        String result = m.replaceAll("");
        return result;
    }

    public static String readAssetsTxt(Context context, String fileName) {
        try {
            //Return an AssetManager instance for your application's package
            InputStream is = context.getAssets().open(fileName);
            int size = is.available();
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            // Convert the buffer into a string.
            String text = new String(buffer, "utf-8");
            // Finally stick the string into the text view.
            return text;
        } catch (IOException e) {
            // Should never happen!
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        return "{\"ResultData\":\"读取错误，请检查文件名！\",\"Success\":true,\"ReturnMsg\":\"读取错误，请检查文件名！\"}";
    }

    public static void createDirectory(File var0) {
        if (!var0.exists()) {
            File var1 = var0.getParentFile();
            boolean var2;
            if (null != var0 && var1.exists()) {
                if (!var1.isDirectory()) {
                    var1.delete();
                    var2 = var1.mkdir();
                    if (!var2) {
                        var1.delete();
                    }
                }

                var2 = var0.mkdir();
                if (!var2) {
                    var0.delete();
                }
            } else {
                createDirectory(var0.getParentFile());
                var2 = var0.mkdir();
                if (!var2) {
                    var0.delete();
                }
            }

        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermission();
        createDirectory(new File(AudioPickerManager.getSignaturePath()));

        path = Environment.getExternalStorageDirectory().getPath() + path;
        PickerConfig config = new PickerConfig()
                .setPickerMaxNum(3)
                .setPickerNumColumns(3);

        pickerFragment = AudioFragment.newInstance("语音附件", 60).initConfig(config);

        getSupportFragmentManager().beginTransaction().replace(R.id.fr_content_image,
                pickerFragment)
                .commit();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        StringBuffer strbuf = new StringBuffer();
        strbuf.append("memoryClass " + activityManager.getMemoryClass() + "M");
        strbuf.append("\nlarge Amemory " + activityManager.getLargeMemoryClass() + "M");
        TextView textView = findViewById(R.id.tv_title);
        textView.setText(strbuf.toString());
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, 200);
                    return;
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == 200) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, 200);
                    return;
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清空音频文件
        pickerFragment.clearAudioFile();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 200) {
            checkPermission();
        }
    }
}